# -*- coding: utf-8 -*-

import sys, wx, webbrowser  
import urllib2, re, time, BalloonTip as BT

ID_ICON_TIMER = wx.NewId()  
OK_CLICK = wx.NewId()  
CANCEL_CLICK = wx.NewId()  
OPEN_BROWER=wx.NewId()  
OPEN_PREFS=wx.NewId()  
TIMER_ID = wx.NewId()

MARKET_TIME = [((9,30),(11,35)), ((13,0), (15,5))]
DONATE_URL = "https://www.alipay.com"


class StockTaskBarIcon(wx.TaskBarIcon):  

		def __init__(self, parent):  
				wx.TaskBarIcon.__init__(self)  
				self.parentApp = parent  
				self.Icon = wx.Icon("./stock.png",wx.BITMAP_TYPE_PNG)
				self.CreateMenu()
				self.SetIconImage()

		def CreateMenu(self):  
				self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.ShowMenu)  
				self.Bind(wx.EVT_MENU, self.parentApp.OpenBrowser, id=OPEN_BROWER)  
				self.Bind(wx.EVT_MENU, self.parentApp.OpenPrefs, id=OPEN_PREFS)  
				self.menu=wx.Menu()
				if self.parentApp.url == DONATE_URL or self.parentApp.url.strip() == "":
						self.menu.Append(OPEN_BROWER, "Donate!Alipay Acc:hoooooosety","THANK YOU FOR USING STOCKOVERSEE.DONATE APPRECIATEDDONATE")  
				else:
						self.menu.Append(OPEN_BROWER, "Open Trade Browers","Open a tab explorer for trading stocks.")  
				self.menu.Append(OPEN_PREFS, "Open Preferences")
				self.menu.AppendSeparator()  
				self.menu.Append(wx.ID_EXIT, "Close App")  

		def ShowMenu(self,event):  
				self.PopupMenu(self.menu)  

		def SetIconImage(self):  
				#UpdateTime = time.strftime("%b %d %H:%M", time.localtime())
				self.SetIcon(self.Icon)
				
class MainFrame(wx.Frame):  

		def __init__(self, parent, id, title):  
#				wx.Frame.__init__(self, parent, -1, title, size = (1, 1),  
#            style=wx.FRAME_NO_TASKBAR|wx.NO_FULL_REPAINT_ON_RESIZE)  

				self.codes = []
				self.url = ""
				try:
						self.settingFile = file("settings.ini", "r")
						lines = self.settingFile.readlines()
						self.codes.extend(map(str.strip, lines[0].split(",")))
						if len(lines) == 2:
								self.url = lines[1]
				except IOError:
						self.settingFile = file("settings.ini", "w")
						self.codes = ["000000", "000000", "000000", "000000"]
						self.url = DONATE_URL
						self.settingFile.writelines([",".join(self.codes) + "\n", self.url])
						self.settingFile.close()
				
				self.settingFile.close()
				wx.Frame.__init__(self, parent, -1, title, pos=(100, 100), size=(200,200)) 
				
				self.panel = wx.Panel(self, -1)
				self.codeLabel1 = wx.StaticText(self.panel, -1, "Code_1:")
				self.codeText1 = wx.TextCtrl(self.panel, -1, self.codes[0])
				
				self.codeLabel2 = wx.StaticText(self.panel, -1, "Code_2:")
				self.codeText2 = wx.TextCtrl(self.panel, -1, self.codes[1])
				
				self.codeLabel3 = wx.StaticText(self.panel, -1, "Code_3:")
				self.codeText3 = wx.TextCtrl(self.panel, -1, self.codes[2])
				
				self.codeLabel4 = wx.StaticText(self.panel, -1, "Code_4:")
				self.codeText4 = wx.TextCtrl(self.panel, -1, self.codes[3])
				
				self.urlLabel = wx.StaticText(self.panel, -1, "Trade_Url:")
				self.urlText = wx.TextCtrl(self.panel, -1, self.url, name="url")
				
				self.CodeLabel = [self.codeLabel1, self.codeLabel2, self.codeLabel3, self.codeLabel4]
				self.CodeText = [self.codeText1, self.codeText2, self.codeText3, self.codeText4]
				
				self.okBtn = wx.Button(self.panel, -1, "OK")
				self.Bind(wx.EVT_BUTTON, self.OnOkClick, self.okBtn)
				
				self.cancelBtn = wx.Button(self.panel, -1, "Cancel")
				self.Bind(wx.EVT_BUTTON, self.OnCancelClick, self.cancelBtn)
				
				self.sizer = wx.FlexGridSizer(cols=2,hgap=16,vgap=16)
				
				for i in xrange(4):
						self.sizer.Add(self.CodeLabel[i])
						self.sizer.Add(self.CodeText[i])
				
				self.sizer.AddMany([(self.urlLabel, 0, wx.EXPAND | wx.ALL),\
														(self.urlText, 0, wx.EXPAND | wx.ALL),\
														(self.okBtn, 0, wx.EXPAND | wx.ALL),\
														(self.cancelBtn, 0, wx.EXPAND | wx.ALL)],\
														)

				self.panel.SetSizer(self.sizer)
				
				self.tbicon = StockTaskBarIcon(self)  
				self.tbicon.Bind(wx.EVT_MENU, self.exitApp, id=wx.ID_EXIT)   
				
				self.RefreshBallon(is_init=True)
				
				self.InitTimer()
				#self.tip.ShowTips()
				
				self.Show(False)  
				
		def InitTimer(self):
				self.timer = wx.Timer(self, TIMER_ID)
				self.timer.Start(1000 * 60 * 5)
				wx.EVT_TIMER(self, TIMER_ID, self.OnTimer)
				
		def InMarketTime(self):
				hour, minute = time.localtime()[3:5]
					
				for one in MARKET_TIME:
						if one[0] < (hour, minute) < one[1]:
								return True
				
		def RefreshBallon(self, is_init=False):
				_toptitle = "Update time : %s" % time.strftime("%b %d %H:%M", time.localtime())
				color_txt = []
				for i in xrange(len(self.codes)):
						if self.codes[i].strip() == "000000":
								continue
						info = self.GetInfo(self.codes[i])
						if info:
								PR, chg, chr = info
								txt = (self.codes[i] + " - PR : %s,  chg : %s, chr : %s") % info + "\n"
								color_txt.append((txt, self.GetMessageColour(float(chg))))
						else:
								txt = "STOCK CODE : %s NOT INVALIABLE!" % self.codes[i]
								color_txt.append((txt, wx.LIGHT_GREY))
								break
						
				if is_init:
						if len(color_txt) == 0:
								txt = "    NO STOCK CODE SET."
								color_txt.append((txt, wx.LIGHT_GREY))
						self.tip = BT.BalloonTip(toptitle=_toptitle, coloredmessage=color_txt, shape=BT.BT_RECTANGLE, tipstyle=BT.BT_LEAVE)
						self.tip.SetTarget(self.tbicon)
						self.tip.SetStartDelay(1000)
									
				self.tip.SetBalloonTitle(_toptitle)
				self.tip.SetColorMessage(color_txt)
				
		def UpdateSettings(self):
				self.settingFile = file("settings.ini", "w")
				self.settingFile.writelines([",".join(self.codes) + "\n", self.url])
				#self.settingFile.close()
				
		def OnOkClick(self, event):
				
				self.codes = []
				self.url = ""
				for one_ctrl in self.CodeText:
						if one_ctrl.IsEmpty():
								pass
								#warning 
						else:
								self.codes.append(one_ctrl.GetValue())
				
				self.url = self.urlText.GetValue()
				
				if self.url[0:4] != "http://":
						self.url = "http://" + self.url
				
#				try:
#						urllib2.urlopen(self.url)
#				except urllib2.URLError:
#						warningDlg = wx.MessageDialog(self, "The Url: %s is not avaliable." % self.url,\
#													 "Warning", wx.OK | wx.ICON_HAND)
#						warningDlg.ShowModal()
#						warningDlg.Destroy()
#						self.url = DONATE_URL
#						return
#				except ValueError:
#						warningDlg = wx.MessageDialog(self, "Unknown url type -- %s" % self.url,\
#													 "Warning", wx.OK | wx.ICON_HAND)
#						warningDlg.ShowModal()
#						warningDlg.Destroy()
#						return
						
				if self.url != DONATE_URL:
						menu_item = self.tbicon.menu.FindItemById(OPEN_BROWER)
						menu_item.SetItemLabel("Open Trade Browers")
						menu_item.SetHelp("Open a tab explorer for trading stocks.")
						
				self.Show(False)
				self.RefreshBallon()
				self.UpdateSettings()
				
				event.Skip()
				
		def OnCancelClick(self, event):
				self.Show(False)
				event.Skip()
				
		def OnTimer(self, event):
				if self.InMarketTime():
						self.RefreshBallon()
				event.Skip()
				
		def GetMessageColour(self, chg):
				if chg > 0:
						return wx.RED
				elif chg < 0:
						return wx.GREEN
				return wx.BLACK
						
		def exitApp(self,event):  
				self.tbicon.RemoveIcon()  
				self.tbicon.Destroy()  
				sys.exit()  
				
		def GetInfo(self, id):
				try:
						if id[0] == "0":
								url = "http://www.google.com/finance?client=ig&q=SHE:%s" % id
						elif id[0] == "6":
								url = "http://www.google.com/finance?client=ig&q=SHA:%s" % id
						link = urllib2.urlopen(url)
						result = link.read()
						PatternPR = '(?<=<span class="pr" id="ref_([0-9]{6})_l">).*?(?=</span>)'
						PatternCHG = '(?<=<span class="ch([rg])" id="ref_([0-9]{6})_c">).*?(?=</span>)'
						PatternCHR = '(?<=<span class="ch([rg])" id="ref_([0-9]{6})_cp">).*?(?=</span>)'
						
						pr = re.search(PatternPR, result).group(0)
						chg = re.search(PatternCHG, result).group(0)
						chr = re.search(PatternCHR, result).group(0)
						
						link.close()
				except urllib2.URLError, err:
						errCode, reason = err.reason
						if errCode == 11001:
								warningDlg = wx.MessageDialog(self, "MAKE SURE you have a connect network..." ,\
															 "Warning", wx.OK | wx.ICON_HAND)
								warningDlg.ShowModal()
								warningDlg.Destroy()
				except AttributeError:
						warningDlg = wx.MessageDialog(self, "CODE : %s may be a wrong stock code.\nUse the correct one and setup in the Open Preferences Menu" % id,\
													 "Warning", wx.OK | wx.ICON_HAND)
						warningDlg.ShowModal()
						warningDlg.Destroy()
				else:
						return (pr, chg, chr)

		def OpenBrowser(self,event):
				self.url = self.url.strip()
				if self.url == "":
						webbrowser.open(DONATE_URL)
				else:
						webbrowser.open(self.url)

		def OpenPrefs(self,event):  
				self.Show(True)
				


#---------------- run the program -----------------------  
def main(argv=None):  
		app = wx.App(False)  
		frame = MainFrame(None, -1, 'Stock Oversee Setting')  
		app.MainLoop()  

if __name__ == '__main__':  
		main()